package com.wh.wisdomsite.xbox.server.manager;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wh.wisdomsite.xbox.us.entity.User;
import com.wh.wisdomsite.xbox.us.service.IUserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * UserMapManager
 * 用于在应用启动时在内存中创建userMap，并从数据库中查询出所有的user保存在userMap中，作为系统缓存，在
 * 其他地方需要根据userId查找用户的loginName时能快速响应
 *
 * @version V1.0
 * @Package: com.wh.wisdomsite.xbox.server.manager
 * @author: 丁奕
 * @date: 2018-09-07 10:44
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 **/
public class UserMapManager extends HttpServlet {

    private static final Log logger = LogFactory.getLog(UserMapManager.class);

    private static Map<String, User> userMap = new HashMap<>();

    @Autowired
    private IUserService iUserService;

    @Override
    public void init(ServletConfig config) {
        logger.debug("================>[UserMapManager]自动加载启动开始.");
        try {
            super.init();
            SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
        } catch (ServletException e) {
            e.printStackTrace();
        }
        // 读取用户表中数据，存放入内存中用map管理
        EntityWrapper<User> ew = new EntityWrapper<>();
        ew.setEntity(new User());
        List<User> userList = iUserService.selectList(ew);
        if(userList != null && !userList.isEmpty()){
            for (User user : userList){
                userMap.put(user.getUsId(), user);
            }
        }
        logger.debug("================>[UserMapManager]自动加载启动结束.");
    }

    public static Map<String, User> getUserMap() {
        return userMap;
    }

    /**
     * 在userMap中更新user（添加或者修改）
     * @param user
     */
    public static void updateUserToMap(User user){
        if(user.getUsId() != null && !user.getUsId().equals("")){
            userMap.put(user.getUsId(), user);
        }
    }

    /**
     * 根据传入的usId在userMap中获取user
     * @param usId
     * @return
     */
    public static User getUserInMap(String usId){
        User user = null;
        if(userMap.containsKey(usId)){
            user = userMap.get(usId);
        }
        return user;
    }

    /**
     * 根据传入的usId在userMap中获取user的loginName
     * @param usId
     * @return
     */
    public static String getUserLoginNameInMap(String usId){
        String loginName = "";
        if(userMap.containsKey(usId)){
            loginName = userMap.get(usId).getLoginName();
        }
        return loginName;
    }
}
